import {defineStore} from 'pinia'
import {
    ContactVo,
    FriendService, GroupMemberListVo, GroupMemberVo,
    HelloService,
    LoginService, MessageQueryCriteria,
    MessageService, MessageVo,
    OpenAPI, PageMessageVo, PageUserApplyVo, PageUserVo, RListRoomGroupVo, RListUserVo, RoomGroupVo, RoomService,
    RString,
    RUserVo, UserApplyCriteria, UserApplyVo, UserQueryCriteria,
    UserService,
    UserVo
} from "/@/api/openapi";
import type {UserLoginDto} from "/@/api/openapi";
import {ElInput, ElMessage, ElNotification} from 'element-plus'
import {WebSocketNewMessage} from "/@/utils/types";
import {RoomTypeEnum} from "/@/utils/enum";
import {useUserFriendStore} from "/@/store";

const userFriendStore = useUserFriendStore();

// 定义状态的类型 一般情况下Pinia会自动推断出state的类型，你就无需定义接口。如果state的数据类型比较复杂，推荐你定义一个接口来描述state的类型
export interface IChatState {
    currentRoomId: number // 后端是long类型。当房间类型出发时。就会出现所有的消息
    currentContact: ContactVo
    type: number,// 表示当前会话框中的是 群聊，还是单聊。1表示群聊 2表示单聊。

    currentGroup: RoomGroupVo | undefined, // 表示当前 群聊的信息。比如房间人数，当前在线人数。等等信息。群组的头像名称
    groupMap: Map<number, RoomGroupVo>

    currentGroupMember: Array<GroupMemberVo> | undefined // 获取群组成员的 成员列表
    groupMemberMap: Map<number, Array<GroupMemberVo>>,

    currentMemberList: Array<GroupMemberListVo> | undefined// @专用
    memberListMap: Map<number, Array<GroupMemberListVo>>
    searchParams: MessageQueryCriteria,
    searchParamsMap: Map<number, MessageQueryCriteria>
    currentFriendUid: string,// 表示当前用户的uid

    currentMessageList: PageMessageVo // 当前会话的所有消息
    currentAllMessageList: Array<MessageVo>

    messageListMap: Map<number, PageMessageVo> // 记录用户当前放入是所有消息
    messageAllListMap: Map<number, Array<MessageVo>> // 记录用户当前放入是所有消息
}

export const useWebSocketStore = defineStore("websocket", {
    state: (): IChatState => ({
        currentRoomId: 0,
        currentContact: {
            roomId: 0,
            type: 0,
            hot_Flag: 0,
            text: "",
            name: "",
            avatar: "",
            activeTime: "",
            unreadCount: 0
        },
        type: 0,
        currentGroup: {},
        groupMap: new Map<number, RoomGroupVo>(),

        currentGroupMember: new Array<GroupMemberVo>(),
        groupMemberMap: new Map<number, Array<GroupMemberVo>>(),

        currentMemberList: new Array<GroupMemberListVo>(),
        memberListMap: new Map<number, Array<GroupMemberListVo>>(),

        searchParams: {pageSize: 100, pageNum: 1, roomId: 0},
        searchParamsMap: new Map<number, MessageQueryCriteria>(),

        currentFriendUid: "",
        currentMessageList: {},
        currentAllMessageList: new Array<MessageVo>(),

        messageListMap: new Map<number, PageMessageVo>(),
        messageAllListMap: new Map<number, Array<MessageVo>>()
    }),

    getters: {},
    actions: {
        // 当有新消息更新时。
        updateNewMessage(data: WebSocketNewMessage) {
            // 第一步，判断当前消息是否存在数据
            const roomId = data.roomId;
            console.log("出现新消息")
            const contact = userFriendStore.contactMap.get(parseInt(String(roomId)));
            // 首先刷新消息列表
            this.updateMessage({
                pageSize: 100,
                pageNum: 1,
                roomId: roomId
            })
            userFriendStore.updateContactByNewMessage(roomId);
            // 表示，当前的数据。已经阅读了
            if (roomId === this.currentRoomId) {
                this.readMessage(roomId)
            } else {
                let msg = "";
                if (contact !== undefined) {
                    msg = contact.name + "发来新消息";
                } else {
                    msg = "发来新消息"
                }
                ElNotification({
                    title: '新消息',
                    message: h('i', {style: 'color: teal'}, msg),
                })
            }
        },

        updateCurrentRoomId() {
            // 首先是阅读了当前房间的记录
            this.readMessage(this.currentRoomId);
            // 更新 朋友用户的当前房间号
            userFriendStore.currentRoomId = this.currentRoomId
            userFriendStore.updateContactByNewMessage(this.currentRoomId)
            // 当发生
            const data = userFriendStore.contactMap.get(this.currentRoomId);
            // 更新数据完毕
            if (data !== undefined) {
                if (data.type !== null) {
                    this.type = data.type
                }
                // 如果存在当前会话
                this.updateContact(data);
                // 如果是群组消息
                if (data.type === RoomTypeEnum.Group) {
                    // 如果有 当前的群组消息。则不重新获取
                    if (this.groupMap.has(this.currentRoomId)) {
                        this.currentGroup = this.groupMap.get(this.currentRoomId);
                    } else {
                        this.updateGroup(this.currentRoomId); // 更新群组信息
                    }
                    // 如果存在当前群组消息，则进行更新
                    if (this.groupMemberMap.has(this.currentRoomId)) {
                        this.currentGroupMember = this.groupMemberMap.get(this.currentRoomId)
                    } else {
                        this.updateGroupMemberList(this.currentRoomId) // 更新群组成员
                    }
                    if (this.memberListMap.has(this.currentRoomId)) {
                        this.currentMemberList = this.memberListMap.get(this.currentRoomId)
                    } else {
                        this.updateMember(this.currentRoomId) // 更新 群组成员 @专用
                    }
                }
                // 消息肯定是每次都更新
                let searchParams: MessageQueryCriteria = {
                    pageNum: 1,
                    pageSize: 10,
                    roomId: this.currentRoomId
                }
                // 更新会话信息
                this.updateMessage({
                    pageSize: 100,
                    pageNum: 1,
                    roomId: this.currentRoomId
                })
            }
        },
        updateMessageOne(data: MessageVo) {
            this.currentAllMessageList.push(data);
        },
        updateContact(data: ContactVo) {
            this.currentContact = data;
        },
        // 获取群组消息。比如在线消息
        updateGroup(roomId: number) {
            RoomService.groupDetail(roomId).then((res) => {
                if (res.code !== 200 || res.data === undefined) {
                    ElMessage({
                        type: 'error',
                        message: res.message,
                    })
                    return;
                }
                if (String(this.currentRoomId) === String(roomId)) {
                    this.currentGroup = res.data
                }
                // 设置最新的数据
                this.groupMap.set(this.currentRoomId, res.data)
            }, (error) => {
                ElMessage({
                    type: 'error',
                    message: error,
                })
            })
        },
        // 更新群组成员。
        updateGroupMemberList(roomId: number) {
            RoomService.getMemberPage(roomId).then((res) => {
                if (res.code !== 200 || res.data === undefined) {
                    ElMessage({
                        type: 'error',
                        message: res.message,
                    })
                    return;
                }
                if (String(this.currentRoomId) === String(roomId)) {
                    this.currentGroupMember = res.data
                }
                this.groupMemberMap.set(roomId, res.data)
            }, (error) => {
                ElMessage({
                    type: 'error',
                    message: error,
                })
            })
        },
        // @专用
        updateMember(roomId: number) {
            RoomService.getMemberList(roomId).then((res) => {
                if (res.code !== 200 || res.data === undefined) {
                    ElMessage({
                        type: 'error',
                        message: res.message,
                    })
                    return;
                }
                if (String(this.currentRoomId) === String(roomId)) {
                    this.currentMemberList = res.data
                }
                // console.log("当前用户群组")
                // console.log(this.currentMemberList)
                // console.log(res.data)
                this.memberListMap.set(roomId, res.data)
            }, (error) => {
                ElMessage({
                    type: 'error',
                    message: error,
                })
            })
        },
        updateMessage(searchParams: MessageQueryCriteria) {
            // 更新消息。设置最新的消息
            MessageService.queryMessage(searchParams).then((res) => {
                if (res.code !== 200 || res.data === undefined || res.data.records === undefined) {
                    ElMessage({
                        type: 'error',
                        message: res.message,
                    })
                    return;
                }
                console.log("更新了消息->")
                console.log(searchParams.roomId, this.currentRoomId, searchParams.roomId === this.currentRoomId)
                // 当前消息
                if (String(searchParams.roomId) === String(this.currentRoomId)) {
                    this.currentMessageList = res.data
                    this.currentAllMessageList = res.data.records
                }
                this.messageListMap.set(searchParams.roomId, res.data);
            }, (error) => {
                ElMessage({
                    type: 'error',
                    message: error,
                })
            })
        },
        readMessage(roomId: number) {
            MessageService.msgRead({roomId: roomId}).then((res) => {
                if (res.code === undefined || res.code !== 200) {
                    ElMessage({
                        type: 'error',
                        message: res.message,
                    })
                }
            }, (error) => {
                ElMessage({
                    type: 'error',
                    message: error,
                })
            }).catch((error) => {
                ElMessage({
                    type: 'error',
                    message: error,
                })
            })
        },
    }
})

